package com.lsh.service;

import com.lsh.model.SysRole;
import com.lsh.model.SysUser;
import com.lsh.model.SysUserRole;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author ：LiuShihao
 * @date ：Created in 2020/11/9 3:09 下午
 * @desc ：自定义的进行认证的具体实现类
 *  * 根据用户名查出对应的角色,将角色信息交给SpringSecurity托管
 *  * 在访问对应资源时就会自动去验证该用户是否有权限访问
 */
// 注入时按名字注入
@Service("userDetailsService")
@Slf4j
public class MyUserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    SysService sysService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据 username 查询数据库  用户信息
        SysUser user = sysService.findUserByUsername(username);
        log.info("用户："+user);
        // 判断用户是否存在
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        // 存在用户   然后根据用户ID查询所有角色信息Id
        List<SysUserRole> rolesId = sysService.findRolesIdByUserID(user.getId());
        // 根据从[用户角色中间表]中查出的角色信息(也就是角色id),
        // 去角色表中查询全部角色名
        // 并将其角色信息放入GrantedAuthority集合
        Collection<GrantedAuthority> authorities = new ArrayList<>();
        for (SysUserRole sysUserRole : rolesId) {
           SysRole role =  sysService.findRoleByRoleId(sysUserRole.getRoleId());
           log.info("角色："+role);
            authorities.add(new SimpleGrantedAuthority(role.getName()));
        }
        /**
         * 返回值是UserDetails，这是一个接口，
         * 一般使用它的子类org.springframework.security.core.userdetails.User，
         * 它有三个参数，分别是用户名、密码和权限集
         */
        return new User(user.getName(), user.getPassword(), authorities);
    }
}
